package org.esk.dablog.web.forms.user;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.validation.BindException;
import org.esk.dablog.service.UserManager;
import org.esk.dablog.model.Author;
import org.esk.dablog.exceptions.ParameterException;
import org.esk.dablog.web.util.RequestUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class
 * User: jc
 * Date: 22.11.2006
 * Time: 12:32:34
 * $Id:$
 */
public class EditUserForm extends SimpleFormController {

    private UserManager userManager;

    public EditUserForm() {
        setCommandClass(Author.class);
    }


    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    /**
     * processes form submission
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param object
     * @param bindException
     * @return
     * @throws Exception
     */
    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, BindException bindException) throws Exception {
        Author bean = (Author) object;
        Author old = userManager.getAuthorById(bean.getId());
        String password = old.getPassword();
        PropertyUtils.copyProperties(old, bean);
        if(StringUtils.isEmpty(old.getPassword())) {
            old.setPassword(password);
        }
        userManager.saveAuthor(old);
        return new ModelAndView(new RedirectView(getSuccessView() + "/" + bean.getUsername(), true));
    }


    /**
     * initializes Entry object from request param. redirects to home page in case of errors
     *
     * @param request
     * @return
     * @throws Exception
     */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        long id = RequestUtils.extractLongParameter(request);
        Author a = userManager.getAuthorById(id);
        Author form = new Author();
        PropertyUtils.copyProperties(form, a);
        return form;
    }

}
